<?php

namespace app\common\model\caijiatong;

use think\Model;
use think\Log;

/**
 * 价格查询
 */
class PriceQuery extends Model
{
    public $es;

    public function __construct($es)
    {
        $this->es = $es;
    }
    /**
     * 根据材料相关信息获取价格
     *
     * @param array $materialData
     * @param integer $marketprice 市场价
     * @param integer $mixprice 综合价
     * @param integer $inquiryprice 他人询价
     * @param integer $govprice 信息价
     * @return array
     */
    function getPriceQuery($materialData, $marketprice = 1, $mixprice = 1, $inquiryprice = 1, $govprice = 1)
    {
        $fax = $mix = $inquiry = $gov = [];
        if (!$materialData  || empty($materialData['title']) ) {
            return ['fax' => $fax, 'mix' => $mix, 'inquiry' => $inquiry, 'gov' => $gov];
        }

        if ($marketprice) {
            $fax = $this->getFaxPrice($materialData);
        }
        if ($mixprice) {
            $mix = $this->getMixPrice($materialData);
        }
        if ($inquiryprice) {
            $inquiry = $this->getInquiryPrice($materialData);
        }
        if ($govprice) {
            $gov = $this->getGovPrice($materialData);
        }
        return ['fax' => $fax, 'mix' => $mix, 'inquiry' => $inquiry, 'gov' => $gov];
    }

    /**
     * 查询匹配材料的市场价数据
     *
     * @param array $materialData
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getFaxPrice($materialData, $page = 1, $size = 1)
    {
        $return = [
            'count' => 0,
            'list' => []
        ];
        $must = [];
        $should = [
            [
                'term' => [
                    'title.kw' =>  [
                        'value' => $materialData['title'],
                        'boost' => 3
                    ]
                ],
            ],
            [
                'match_phrase' => [
                    'title' => [
                        'query' => $materialData['title'],
                        'analyzer' => 'ik_smart',  // 使用ik_smart分词器
                        'boost' => 2   // 提高 title 字段的权重
                    ]
                ]
            ],
            [
                'match' => [
                    'title' => [
                        'query' => $materialData['title'],
                        'minimum_should_match' => '70%', // 至少匹配70%分词
                        'boost' => 1.5
                    ]
                ]
            ]
        ];
        if ($chinese = $this->es_matchChinese($materialData['title'])) {
            $should[] = [
                'match_phrase' => [
                    'title' => [
                        'query' => $chinese,
                        // 'analyzer' => 'ik_smart',  // 使用ik_smart分词器
                        'slop' => 1,
                        'boost' => 4 // 全匹配权重更高
                    ]
                ]
            ];
        }

        $must[] = [
            'bool' => [
                'should' => $should,
                'minimum_should_match' => 1  // 至少满足一个 should 条件
            ]
        ];
        $shouldSpec = [];
        if (!empty($materialData['own_spec'])) {
            $specArr = explode(';', str_replace('；', ';', $materialData['own_spec']));
            foreach ($specArr as $onespec) {
                if (empty($onespec))  continue;
                $a = explode(':', $onespec);
                // 将键和值存储到关联数组中
                if (count($a) != 2) {
                    //没有区分键值对的话，模糊匹配规格值
                    $shouldSpec[] = [
                        'match_phrase' => [
                            'own_specjson.attrValue' => [
                                'query' => $onespec
                            ]
                        ]
                    ];
                    continue;
                }
                $shouldSpec[] = [
                    'prefix' => [
                        'own_specjson.attrName.kw' => [
                            'value' => $a[0]
                        ]
                    ]
                ];
                $shouldSpec[] = [
                    'match_phrase' => [
                        'own_specjson.attrValue.kw' => [
                            'query' => $a[1]
                        ]
                    ]
                ];
            }
        } else {
            $shouldSpec[] = [
                'match' => [
                    'own_specjson.attrValue' => [
                        'query' => $materialData['title'],
                        'analyzer' => 'ik_smart',  // 使用ik_smart分词器ik_max_word
                        'boost' => 2   // 提高 title 字段的权重
                    ]
                ]
            ];
        }
        // 添加 own_spec 的 should 子句到 must
        if (!empty($shouldSpec)) {
            $must[] = [
                'bool' => [
                    'should' => $shouldSpec,
                    'minimum_should_match' => 1  // 至少满足一个 should 条件
                ]
            ];
        }
        // if (!empty($materialData['brandname'])) {
        //     $must[] = [
        //         'term' => [
        //             'brandname' => $materialData['brandname']
        //         ]
        //     ];
        // }
        $filter = [
            [
                'term' => [
                    'status' => [
                        'value' => 'normal'
                    ]
                ]
            ],
            [
                'term' => [
                    'isverify' => [
                        'value' => 1
                    ]
                ]
            ]
        ];
        $body = [
            'query' => [
                'bool' => [
                    'must' => $must,
                    'filter' => $filter,
                    'must_not' => [
                        'exists' => [
                            'field' => 'deletetime'
                        ]
                    ]
                ]
            ],
            'track_total_hits' => true,
            'sort' => [    //字段排序
                [
                    '_score' => [
                        'order' => 'desc'
                    ]
                ],
                [
                    'showdate' => [
                        'order' => 'desc'
                    ]
                ],
            ],
        ];
        $index = '';
        $year = date('Y');
        for ($i = $year; $i <= $year && $i >= 2023; $i--) {
            $index .= 'es_fax_sku_1263_' . $i . ',';
        }
        $index = rtrim($index, ',');
        $params = [
            'index' => $index,
            'body' => $body,
            'from' => ($page - 1) * $size,  //偏移量
            'size' => $size,   //每页多少个
            'search_type'=>'dfs_query_then_fetch'
        ];
        $esSkus = $this->es->search($params);
        $return['count'] = $esSkus['hits']['total']['value'];
        if ($return['count'] > 0) {
            $return['list'] = $esSkus['hits']['hits'];
        }
        return $return;
    }

    /**
     * 查询匹配材料的综合价
     *
     * @param array $materialData
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getMixPrice($materialData, $page = 1, $size = 1)
    {
        $return = [
            'count' => 0,
            'list' => []
        ];
        $must = [];
        $should = [
            [
                'term' => [
                    'title' => $materialData['title']
                ],
            ],
            [
                'match_phrase' => [
                    'title' => [
                        'query' => $materialData['title'],
                        // 'analyzer' => 'ik_smart',  // 使用ik_smart分词器
                        'boost' => 2   // 提高 title 字段的权重
                    ]
                ]
            ],
            // [
            //     'match' => [
            //         'title' => [
            //             'query' => $materialData['title'],
            //             // 'analyzer' => 'ik_smart',
            //             'boost' => 1
            //         ]
            //     ]
            // ]
        ];
        $must[] = [
            'bool' => [
                'should' => $should,
            ]
        ];
        if (!empty($materialData['own_spec'])) {
            $shouldSpec = [];
            $specArr = explode(';', str_replace('；', ';', $materialData['own_spec']));
            foreach ($specArr as $onespec) {
                if (empty($onespec))  continue;
            //    $shouldSpec[] = [
            //        'match' => [
            //            'own_spec' => [
            //                'query' => $onespec
            //            ]
            //        ]
            //    ];
                $shouldSpec[] = [
                    'match_phrase' => [
                        'spec' => [
                            'query' => $onespec,
                            'boost' => 2 
                        ]
                    ]
                ];
                $a = explode(':', $onespec);
                // 将键和值存储到关联数组中
                if (count($a) != 2) {
                    continue;
                }
                $shouldSpec[] = [
                    'match_phrase' => [
                        'own_spec' => [
                            'query' => $a[1]
                        ]
                    ]
                ];
            }
            // 添加 own_spec 的 should 子句到 must
            if (!empty($shouldSpec)) {
                // $must[] = [
                //     'bool' => [
                //         'should' => $shouldSpec,
                //         'minimum_should_match' => 1  // 至少满足一个 should 条件
                //     ]
                // ];
            }
        }
        

        $filter = [
            [
                'term' => [
                    'is_online' => [
                        'value' => 1
                    ]
                ]
            ]
        ];
        $body = [
            'query' => [
                'bool' => [
                    'must' => $must,
                    'filter' => $filter,
                    'must_not' => [
                        'exists' => [
                            'field' => 'deletetime'
                        ]
                    ]
                ]
            ],
            'track_total_hits' => true,
            'sort' => [    //字段排序
                [
                    '_score' => [
                        'order' => 'desc'
                    ]
                ],
                [
                    'verifytime' => [
                        'order' => 'desc'
                    ]
                ],
            ],
        ];
        $index = 'es_fa_mix_sku_1263';

        $params = [
            'index' => $index,
            'body' => $body,
            'from' => ($page - 1) * $size,  //偏移量
            'size' => $size,   //每页多少个
            // 'search_type'=>'dfs_query_then_fetch'
        ];
        $esSkus = $this->es->search($params);
        $return['count'] = $esSkus['hits']['total']['value'];
        if ($return['count'] > 0) {
            $return['list'] = $esSkus['hits']['hits'];
        }
        return $return;
    }


    /**
     * 查询匹配材料的人工询价
     *
     * @param array $materialData
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getInquiryPrice($materialData, $page = 1, $size = 1)
    {
        $return = [
            'count' => 0,
            'list' => []
        ];
        $must = [];
        $should = [
            [
                'term' => [
                    'materialname' => $materialData['title']
                ],
            ],
            [
                'match_phrase' => [
                    'materialname' => [
                        'query' => $materialData['title'],
                        // 'analyzer' => 'ik_smart',  // 使用ik_smart分词器
                        'boost' => 2   // 提高 title 字段的权重
                    ]
                ]
            ],
            // [
            //     'match' => [
            //         'materialname' => [
            //             'query' => $materialData['title'],
            //             // 'analyzer' => 'ik_smart',
            //             'boost' => 1
            //         ]
            //     ]
            // ]
        ];
        $must[] = [
            'bool' => [
                'should' => $should,
            ]
        ];
        if (!empty($materialData['own_spec'])) {
            $shouldSpec = [];
            $specArr = explode(';', str_replace('；', ';', $materialData['own_spec']));
            foreach ($specArr as $onespec) {
                if (empty($onespec))  continue;
            //    $shouldSpec[] = [
            //        'match' => [
            //            'spec' => [
            //                'query' => $onespec
            //            ]
            //        ]
            //    ];
                $shouldSpec[] = [
                    'match_phrase' => [
                        'spec' => [
                            'query' => $onespec,
                            'boost' => 2 
                        ]
                    ]
                ];
                $a = explode(':', $onespec);
                // 将键和值存储到关联数组中
                if (count($a) != 2) {
                    continue;
                }
                $shouldSpec[] = [
                    'match_phrase' => [
                        'spec' => [
                            'query' => $a[1]
                        ]
                    ]
                ];
            }
            // 添加 own_spec 的 should 子句到 must
            if (!empty($shouldSpec)) {
                // $must[] = [
                //     'bool' => [
                //         'should' => $shouldSpec,
                //         'minimum_should_match' => 1  // 至少满足一个 should 条件
                //     ]
                // ];
            }
        }
        
        $filter = [
            [
                'term' => [
                    'isend' => [
                        'value' => 1
                    ]
                ]
            ],
            [
                'term' => [
                    'isdrafts' => [
                        'value' => 0
                    ]
                ]
            ]
        ];
        $body = [
            'query' => [
                'bool' => [
                    'must' => $must,
                    'filter' => $filter,
                    'must_not' => [
                        'exists' => [
                            'field' => 'deletetime'
                        ]
                    ]
                ]
            ],
            'track_total_hits' => true,
            'sort' => [    //字段排序
                [
                    '_score' => [
                        'order' => 'desc'
                    ]
                ],
                [
                    'createtime' => [
                        'order' => 'desc'
                    ]
                ],
            ],
        ];
        $index = 'es_fa_user_inquiry_spec';

        $params = [
            'index' => $index,
            'body' => $body,
            'from' => ($page - 1) * $size,  //偏移量
            'size' => $size,   //每页多少个
            // 'search_type'=>'dfs_query_then_fetch'
        ];
        $esSkus = $this->es->search($params);
        $return['count'] = $esSkus['hits']['total']['value'];
        if ($return['count'] > 0) {
            $return['list'] = $esSkus['hits']['hits'];
        }
        return $return;
    }

    /**
     * 查询匹配材料的信息价
     *
     * @param array $materialData
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getGovPrice($materialData, $page = 1, $size = 1)
    {
        $return = [
            'count' => 0,
            'list' => []
        ];
        $must = [];
        $should = [
            [
                'term' => [
                    'title' => $materialData['title']
                ],
            ],
            [
                'match_phrase' => [
                    'title' => [
                        'query' => $materialData['title'],
                        // 'analyzer' => 'ik_smart',  // 使用ik_smart分词器
                        'boost' => 2   // 提高 title 字段的权重
                    ]
                ]
            ],
            // [
            //     'match' => [
            //         'title' => [
            //             'query' => $materialData['title'],
            //             // 'analyzer' => 'ik_smart',
            //             'boost' => 1
            //         ]
            //     ]
            // ]
        ];
        if ($this->es_matchChinese($materialData['title'])) {
            $should[] = [
                'match_phrase' => [
                    'title' => [
                        'query' => $this->es_matchChinese($materialData['title']),
                        // 'analyzer' => 'ik_smart',  // 使用ik_smart分词器
                        'boost' => 4 // 全匹配权重更高
                    ]
                ]
            ];
        }
        $must[] = [
            'bool' => [
                'should' => $should,
            ]
        ];
        $shouldSpec = [];
        if (!empty($materialData['own_spec'])) {
            $specArr = explode(';', str_replace('；', ';', $materialData['own_spec']));
            foreach ($specArr as $onespec) {
                if (empty($onespec))  continue;
                // $shouldSpec[] = [
                //     'match' => [
                //         'spec' => [
                //             'query' => $onespec,
                //             'minimum_should_match' => '75%', // 至少匹配70%分词
                //             'boost' => 1
                //         ]
                //     ]
                // ];
                $shouldSpec[] = [
                    'match_phrase' => [
                        'spec' => [
                            'query' => $onespec,
                            'boost' => 2 
                        ]
                    ]
                ];
                $a = explode(':', $onespec);
                // 将键和值存储到关联数组中
                if (count($a) != 2) {
                    continue;
                }
                $shouldSpec[] = [
                    'match_phrase' => [
                        'spec' => [
                            'query' => $a[1],
                            'boost' => 1 
                        ]
                    ]
                ];
            }
        } else {
            $shouldSpec[] = [
                'match' => [
                    'spec' => [
                        'query' => $materialData['title'],
                        'minimum_should_match' => '70%', // 至少匹配70%分词
                        'boost' => 1 
                    ]
                ]
            ];
        }
        // 添加 own_spec 的 should 子句到 must
        if (!empty($shouldSpec)) {
            $must[] = [
                'bool' => [
                    'should' => $shouldSpec,
                    'minimum_should_match' => 1  // 至少满足一个 should 条件
                ]
            ];
        }
        
        $filter = [
            [
                'term' => [
                    'status' => [
                        'value' => 'normal'
                    ]
                ]
            ],
            [
                'term' => [
                    'need_verify' => [
                        'value' => 0
                    ]
                ]
            ]
        ];
        $body = [
            'query' => [
                'bool' => [
                    'must' => $must,
                    'filter' => $filter,
                    'must_not' => [
                        'exists' => [
                            'field' => 'deletetime'
                        ]
                    ]
                ]
            ],
            'track_total_hits' => true,
            'sort' => [    //字段排序
                [
                    '_score' => [
                        'order' => 'desc'
                    ]
                ],
                [
                    'year' => [
                        'order' => 'desc'
                    ]
                ],
                [
                    'month' => [
                        'order' => 'desc'
                    ]
                ],
            ],
        ];
        $index = 'es_fa_gov_sku_1263';

        $params = [
            'index' => $index,
            'body' => $body,
            'from' => ($page - 1) * $size,  //偏移量
            'size' => $size,   //每页多少个
            // 'search_type'=>'dfs_query_then_fetch'
        ];
        $esSkus = $this->es->search($params);
        $return['count'] = $esSkus['hits']['total']['value'];
        if ($return['count'] > 0) {
            $return['list'] = $esSkus['hits']['hits'];
        }
        return $return;
    }

    protected function es_matchChinese($str)
    {
        $pattern = '/[\x{4e00}-\x{9fa5}]+/u'; // 正则表达式匹配中文

        // 使用preg_match_all查找所有匹配项
        if (preg_match_all($pattern, $str, $matches)) {
            $chinese = implode('', $matches[0]); // 将匹配项拼接成一个字符串
            return $chinese; // 返回匹配到的中文
        } else {
            return null;
        }
    }
}
